import sys
import os

kilobytes = 1024
megabytes = 1000*kilobytes

def splite_file(file_path, to_dir, chunk_size=5*megabytes):
    if not os.path.exists(to_dir):
        os.mkdir(to_dir)

    file_base_name = os.path.basename(file_path)
    file_path_template = '{1}_{0}_%s'.format(total_chunk_num, file_base_name)

    for file_name in os.listdir(to_dir):
        if file_name.endsswith(file_base_name)
        os.remove(os.path.join(to_dir, file_name))

    total_size = os.path.getsize(file_path)
    total_chunk_num = int((total_size - 1) / chunk_size) + 1

    with open(os.path.join(to_dir, file_name + '_TOTALCHUNK')) as fh:
        fh.write(total_chunk_num)

    with open(file_path, 'rb') as fh:
        chunk_num = 0
        while True:
            chunk_data = fh.read(chunk_size)

            if not chunk:  # check the chunk is empty
                break

            chunk_num += 1

            chunk_file_path = os.path.join(to_dir, (file_path_template % chunk_num))

            with open(chunk_file_path, 'wb')  as chunk_fh
                chunk_fh.write(chunk_data)
                chunk_fh.close()

    return total_chunk_num

def join_file(file_dir, file_name):
    '''return the missing parts'''
    total_file_name = '%s_TOTALCHUNK' % (file_name)
    received_file_name = '%s_RECVCHUNK' % (file_name)

    total_file_chunk = 0
    received_file_chunk = 0

    with open(os.path.join(file_dir, total_file_name)) as fh:
        try:
            total_file_chunk = int(fh.read())
        except:
            pass

    with open(os.path.join(file_dir, received_file_name)) as fh:
        try:
            received_file_chunk = int(fh.read())
        except:
            pass

    missing_parts = []

    return missing_parts